package com.zengqingfa.examples.mybatisplus.interceptor;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.zengqingfa.examples.mybatisplus.util.ThreadContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @fileName: RequestInterceptor
 * @author: zengqf3
 * @date: 2021-6-30 13:40
 * @description:
 */
public class RequestInterceptor extends HandlerInterceptorAdapter {

    public static final String TRACE_ID = "traceId";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置要放到MDC中的参数
        String val = request.getHeader(TRACE_ID);
        if (!StringUtils.isEmpty(val)) {
            MDC.put(TRACE_ID, val);
        } else {
            val = UUID.randomUUID().toString();
            MDC.put(TRACE_ID, val);
        }
        ThreadContext.getContext().set(val);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception {
        MDC.clear();
        ThreadContext.getContext().remove();
    }
}